import { create, remove, update, query } from '../services/costs'
import { parse } from 'qs'
export default {
  namespace: 'costs',
  state: {
    list: [],
    currentItem: {},
    modalVisible: false,
    modalType: 'create',
    isMotion: localStorage.getItem('antdAdminCostIsMotion') === 'true',
    pagination: {
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: total => `共 ${total} 条`,
      current: 1,
      total: null
    }
  },
  reducers: {
    querySuccess (state, action) {
      const {list, pagination} = action.payload
      return { ...state,
        list,
        pagination: {
          ...state.pagination,
          ...pagination
        }}
    },
    showModal (state, action) {
      console.log(action);

      return { ...state, ...action.payload, modalVisible: true }
    },
    hideModal (state) {
      return { ...state, modalVisible: false }
    },
    handleSwitchIsMotion (state) {
      localStorage.setItem('antdAdminCostIsMotion', !state.isMotion)
      return { ...state, isMotion: !state.isMotion }
    }
  },
  effects: {
    *query ({ payload }, { call, put }) {
      const data = yield call(query, parse(payload));
      if (data) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data
          }
        })
      }
    },
    *delete ({ payload }, { call, put }) {
      const data = yield call(remove, { id: payload })
      if (data.Id || data === 'OK') {
        const newData = yield call(query, parse(payload));
        yield put({
          type: 'querySuccess',
          payload: {
            list: newData
          }
        })
      }
    },
    *create ({ payload }, { call, put }) {
      yield put({ type: 'hideModal' })
      const data = yield call(create, payload)
      if (data.Id || data === 'OK') {
        const newData = yield call(query, parse(payload));
        yield put({
          type: 'querySuccess',
          payload: {
            list: newData
          }
        })
      }
    },
    *details ({ payload }, { select, call, put }) {
      yield put({ type: 'hideModal' });
      const id = yield select(({ costs }) => costs.currentItem.Id);
      const newCost = { ...payload, id };
      const data = yield call(update, newCost);
      if (data.Id || data === 'OK') {
        const newData = yield call(query, parse(payload));
        yield put({
          type: 'querySuccess',
          payload: {
            list: newData
          }
        })
      }
    },
    *switchIsMotion ({
                             payload
                           }, {put}) {
      yield put({
        type: 'handleSwitchIsMotion'
      })
    }
  },

  subscriptions: {
    setup ({ dispatch, history }) {
      history.listen(location => {
        if (location.pathname === '/costs') {
          dispatch({
            type: 'query',
            payload: location.query
          })
        }
      })
    }
  },
};
